import Vue from 'vue';
/* entity */
import Customer from '@model/entity/Customer'
import LoginUser from '@model/entity/LoginUser/LoginUser'
import Task from '@model/entity/Task'
import TaskApprove from '@model/entity/TaskApprove'
import TaskType from '@model/entity/TaskType'
import EsTask from '@model/entity/EsTask'
/* enum */
import AuthEnum from '@model/enum/AuthEnum'
import AuthValueEnum from '@model/enum/AuthValueEnum'
import { 
  CommonMappingEnum,
  CustomerFieldNameMappingEnum, 
  FieldTypeMappingEnum, 
  ProductFieldNameMappingEnum,
  TagEntityMappingEnum,
  TaskFieldNameMappingEnum,
} from '@model/enum/FieldMappingEnum'
import TaskStateEnum from '@model/enum/TaskStateEnum'
import LeaderEnum from '@model/enum/LeaderEnum'
import AllotTypeEnum from '@model/enum/AllotTypeEnum'
/* service */
import { getFieldName } from '@service/FieldService'
/* types */
import FlowSetting from '@model/types/FlowSetting'
/* util */
import { isArray, isString } from '@src/util/type'
import { getRootWindowInitData } from '@src/util/window'
import Log from '@src/util/log.ts'
import { openTabForTaskAllot, openTabForTaskView } from '@src/util/business/openTab'
import Field from '@model/entity/Field'
import { fmt_form_cascader } from '@src/filter/form'
import i18n from '@src/locales'
import { formatAddress } from 'pub-bbx-utils';

/**
 * @description 检查审批
*/
export function checkApprove(taskType: TaskType, action: string, task: Task | null, customer: Customer | null): TaskApprove {
	let needApprove: boolean = false
	let flowSetting: any = taskType.flowSetting
	let result: TaskApprove = { needApprove }

  // 验证是否存在匹配的流程节点信息
	if (flowSetting && !flowSetting[action]) return result

	// 当前节点流程
	let currentFlowSetting: FlowSetting = flowSetting[action]
	if (!currentFlowSetting.state) return result

	result.needApprove = checkIsNeedApprove(currentFlowSetting, task, customer, result)
	result.approversName = getApproversName(currentFlowSetting, task, result)
	result.taskId = task?.id || ''

	return result
}

/**
 * @description 是否需要审批
*/
function checkIsNeedApprove(flowSetting: FlowSetting, task: Task | null, customer: Customer | null, result: any = {}): boolean {
	let { leader = '', approvers, vipApprove = 0 } = flowSetting
	// 审批人列表是否是空的
	let isEmptyApprovers = isArray(approvers) ? approvers.length <= 0 : false
	// 表单字段 人员字段
	let isFormUser = leader.indexOf(LeaderEnum.FormUser) > -1
	// 客户负责人
	let isCustomerManager = leader === LeaderEnum.UserAdmin
	// 发起人选择
	let isPromoter = leader ===  LeaderEnum.Promoter
	// 是否需要审批
	let isNeedApprove = Boolean(
		(!isEmptyApprovers && (leader == LeaderEnum.Users || isFormUser))
		|| leader === LeaderEnum.Leader
		|| leader ===  LeaderEnum.CreateUser
		|| leader ===  LeaderEnum.AllotUser
		|| isPromoter
		|| isCustomerManager
		|| (!leader && !isEmptyApprovers)
	)

    // 高级审批
    if(vipApprove == 1) return true

  // 无审批人
	if (!leader && isEmptyApprovers) {
		return false
	}

	// 客户负责人
	if (isCustomerManager && customer) {
		let { customerManager } = customer
		return Boolean(customerManager)
	}

	// 工单表单 人员字段
	if (isFormUser && task) {
		let { attribute = {} } = task
		let formUserValue = attribute[leader]
		return Boolean(formUserValue)
	}

	if (isPromoter) {
		// 后端这么写的 用来判断是否是审批发起人选择
		result.isOpt = 1
	}

	return isNeedApprove
}

/* 初始数据 */
const InitData = getRootWindowInitData()

// 有重复的代码，后续优化

/**
 * @description 获取data对象的某个字段的string形式
 * 照搬的后端 base -> TaskService getFieldValue2string 方法
 * @param {Object} data
 * @param {string} fieldName
 * @param {string} formType
 * @param {Array} fields 字段列表
 * @return
*/
export function getFieldValue2string(data: any, fieldName: string, formType: string, fields = [], isCustomerRelation: Boolean): string {
  // 判断字段名称是否存在
  if (!fieldName) return ''
  // 是否是客户模块，暂时先这么判断
  let isCustomerModule: Boolean = isCustomerRelation
  
  return (
    isCustomerModule
      ? getCustomerFieldValue2string(data, fieldName, formType, fields) 
      : getProductFieldValue2string(data, fieldName, formType, fields)
  )
}

/**
 * @description 获取客户的某个字段的string形式
 * @param {Object} data 数据
 * @param {string} fieldName 字段名称
 * @param {string} formType 字段类型
 * @param {Array} fields 字段列表
 * @return
*/
function getCustomerFieldValue2string(data: any, fieldName: string, formType: string, fields = []): string {
  // 客户数据
  const Customer: any = data || {};
  // 返回结果
  let result: string = ''
  // 团队
  if (fieldName == CustomerFieldNameMappingEnum.Tags) {
    let tags = Customer[CustomerFieldNameMappingEnum.Tags] || []
    result = tags.map((tag: any) => tag[TagEntityMappingEnum.TagName]).join(',')
  }
  // 编号
  else if (fieldName == CustomerFieldNameMappingEnum.SerialNumber) {
    result = Customer[CustomerFieldNameMappingEnum.SerialNumber] || ''
  }
  // 客户负责人
  else if (fieldName == CustomerFieldNameMappingEnum.CustomerManager) {
    result = Customer[CustomerFieldNameMappingEnum.CustomerManagerName] || ''
  }
  // 其他字段
  else {
    const Attribute: any = Customer[CommonMappingEnum.Attribute] || {}
    // 地址类型
    if (formType == FieldTypeMappingEnum.Address) {
      let addressData = Attribute[fieldName] || {}
      result = addressData?.all || ''
    }
    // 说明信息类型
    else if (formType == FieldTypeMappingEnum.Info) {
      let infoField: any = fields.filter((field: any) => field.fieldName == fieldName)
      result = infoField?.[0]?.placeholder || ''
    }
    // 位置类型
    else if (formType == FieldTypeMappingEnum.Location) {
      let locationData = Attribute[fieldName] || {}
      result = locationData?.address || ''
    }
    // 人员类型
    else if (formType == FieldTypeMappingEnum.User) {
      let attributeValue = Attribute[fieldName] || {}
      let isMuti = Array.isArray(attributeValue) // 多选
      result = isMuti ? attributeValue.map((i: any) => i.displayName).join(',') : attributeValue?.displayName || ''
    }
    // 关联工单
    else if (formType == FieldTypeMappingEnum.RelatedTask) {
      let attributeValue = Attribute[fieldName] || []
      result = attributeValue.map((i: any) => i.taskNo).join(',')
    }
    // 多级菜单
    else if (formType == FieldTypeMappingEnum.Cascader) {
      let currField: any = fields?.find((field: any) => field.fieldName == fieldName) || {}
      let isMulti = currField.setting?.isMulti
      let displayMode = currField.setting?.displayMode
      let attributeValue = Attribute[fieldName] || []
      result = fmt_form_cascader(attributeValue, isMulti, displayMode)
    } else if (formType == FieldTypeMappingEnum.RelatedCustomers) {
      // 客户关联字段里面的关联客户
      let attributeValue = Attribute[fieldName] || {}
      let isMuti = Array.isArray(attributeValue) // 多选
      result = isMuti ? attributeValue.map((i: any) => i.name).join(',') : attributeValue?.name || ''
    }
    // 其他自定义字段
    else {
      let attributeValue = Attribute[fieldName];
      let isStringArray = Array.isArray(attributeValue) && attributeValue.every(item => isString(item))
      result = isStringArray ? attributeValue.join(',') : attributeValue || ''
    }
  }
  
  return result
}

/**
 * @description 获取产品的某个字段的string形式
 * @param {Object} data 数据
 * @param {string} fieldName 字段名称
 * @param {string} formType 字段类型
 * @param {Array} fields 字段列表
 * @return
*/
// 注：产品注册也用到了该方法
function getProductFieldValue2string(data: any, fieldName: string, formType: string, fields = []): string {
  // 产品数据
  const Product: any = data || {}
  // 返回结果
  let result: string = ''
	
  // 编号
  if (fieldName == ProductFieldNameMappingEnum.SerialNumber) {
    result = Product[ProductFieldNameMappingEnum.SerialNumber] || ''
  }
  // 产品类型
  else if (fieldName == ProductFieldNameMappingEnum.Type) {
    result = Product[ProductFieldNameMappingEnum.CatalogPathNam] || Product[ProductFieldNameMappingEnum.Type] || ''
  }
  else if (!fieldName.startsWith('field_') && Product[fieldName]) {
    result = Product[fieldName]
  }
  // 产品负责人
  else if (fieldName == ProductFieldNameMappingEnum.ProductManager) {
    result = Product[ProductFieldNameMappingEnum.ProductManagerName] || ''
  }
  // 其他字段
  else {
    const Attribute: any = Product[CommonMappingEnum.Attribute] || {}
    let attributeValue = Attribute[fieldName];
    if (!attributeValue && formType !== FieldTypeMappingEnum.Info) return result;

    // 地址类型
    if (formType == FieldTypeMappingEnum.Address) {
      // let attributeValue = Attribute[fieldName] || {}
      result = attributeValue?.all || formatAddress(attributeValue,'') || ''
    }
    // 说明信息类型
    else if (formType == FieldTypeMappingEnum.Info) {
      let infoField: any = fields.filter((field: any) => field.fieldName == fieldName)
      result = infoField?.[0]?.placeholder || ''
    }
    // 位置类型
    else if (formType == FieldTypeMappingEnum.Location) {
      // let attributeValue = Attribute[fieldName] || {}
      result = attributeValue?.address || ''
    }
    // 人员类型
    else if (formType == FieldTypeMappingEnum.User) {
      // let attributeValue = Attribute[fieldName]
      let isMuti = Array.isArray(attributeValue) // 多选
      result = isMuti ? attributeValue.map((i: any) => i.displayName).join(',') : attributeValue?.displayName || ''
    }
    // 关联工单
    else if (formType == FieldTypeMappingEnum.RelatedTask) {
      // let attributeValue = Attribute[fieldName] || []
      result = attributeValue.map((i: any) => i.taskNo).join(',')
    }
    // 多级菜单
    else if (formType == FieldTypeMappingEnum.Cascader) {
      let currField: any = fields?.find((field: any) => field.fieldName === fieldName) || {}
      let isMulti = currField.setting?.isMulti
      let displayMode = currField.setting?.displayMode
      let isStringArray = Array.isArray(attributeValue) && (!attributeValue.length || attributeValue.every(item => isString(item)))
      result = isStringArray ? fmt_form_cascader(attributeValue, isMulti, displayMode) : attributeValue || ''
    }
    // 其他自定义字段
    else {
      // let attributeValue = Attribute[fieldName];
      let isStringArray = Array.isArray(attributeValue) && attributeValue.every(item => isString(item))
      result = isStringArray ? attributeValue.join(',') : attributeValue || ''
    }
  }
	
  return result;
}

/** 
 * @description 获取审批人名称
*/
function getApproversName(flowSetting: FlowSetting, task: Task | null, result: any = {}): string {
  let { leader = '', approvers = [], taskTemplateId } = flowSetting
  let approversName = ''
	
  // 按指定人员
  if (leader === LeaderEnum.Users) {
    approversName = approvers.map((user: LoginUser) => user.displayName).join(', ')
    return approversName
  }
  
  // 客户负责人
  if (leader === LeaderEnum.UserAdmin) {
    approversName = i18n.t('common.form.preview.qualityField.label11') as string
    return approversName
  }
  
  // 由发起人选择
  if (leader === LeaderEnum.Promoter) {
    approversName = i18n.t('common.placeholder.select') as string
    // 后端这么写的 用来判断是否是审批发起人选择
    result.isOpt = 1
    return approversName
  }
  
	// 发起人团队主管
	if (leader === LeaderEnum.Leader) {
		approversName = i18n.t('task.model.promoterDepartmentManager') as string
		return approversName
	}
  
  // 工单创建人
  if (leader === LeaderEnum.CreateUser) {
    approversName = i18n.t('task.setting.taskTypeSetting.flow.components.taskCreator') as string
    return approversName
  }
  
  // 工单派单人
  if (leader === LeaderEnum.AllotUser) {
    approversName = i18n.t('task.setting.taskTypeSetting.flow.components.taskDispatcher') as string
    return approversName
  }
  
  // 表单字段 人员字段
  if (leader.indexOf(LeaderEnum.FormUser) > -1 && taskTemplateId && task) {
    let { attribute = {} } = task
    let formUserValue = attribute[leader]
    approversName = formUserValue
    return approversName
  }
  
  // 其他
  approversName = approvers.map((user: LoginUser) => user.displayName).join(', ')
  
  return approversName
}

/** 
 * @description 是否是工单创建人
*/
export function isCreator(task: any = {}): boolean {
  let loginUser = InitData?.user || { userId: null }
  let createUser = task?.createUser || {}
  // 工单创建人存在 且 登录用户存在 且 相等
  return createUser.userId && loginUser.userId && createUser.userId == loginUser.userId
}

/**
 * @description 是否为已关闭的工单
 * @param {Record} task 工单数据
 * @return {Boolean}
 */
export function isClosedTask(task: Record<string, any> = {}): boolean {
  try {
    return task?.state === TaskStateEnum.CLOSED.value
  } catch (error) {
    Log.error(error, isClosedTask.name)
    return false
  }
}

/**
 * @description 是否为审批中的工单
 * @param {Record} task 工单数据
 * @return {Boolean}
 */
export function isInApprove(task: Record<string, any> = {}): boolean {
  try {
    return task?.inApprove === 1
  } catch (error) {
    Log.error(error, isClosedTask.name)
    return false
  }
}

/**
 * @description 是否为暂停中的工单
 * @param {Record} task 工单数据
 * @return {Boolean}
 */
export function isPaused(task: Record<string, any> = {}): boolean {
  try {
    return task?.isPaused === 1
  } catch (error) {
    Log.error(error, isClosedTask.name)
    return false
  }
}

/**
 * @description 是否自动分配
 * @param {AllotTypeEnum} allotType 指派类型
 * @return {Boolean}
 */
export function isAllotAuto(allotType: AllotTypeEnum): boolean {
  return allotType === AllotTypeEnum.Auto
}

/**
 * @description 是否派单到负责人
 * @param {AllotTypeEnum} allotType 指派类型
 * @return {Boolean}
 */
export function isAllotExecutor(allotType: AllotTypeEnum): boolean {
  return allotType === AllotTypeEnum.Normal
}

/**
 * @description 是否派单到工单池
 * @param {AllotTypeEnum} allotType 指派类型
 * @return {Boolean}
 */
export function isAllotTaskPool(allotType: AllotTypeEnum): boolean {
  return allotType === AllotTypeEnum.Pool
}

/**
 * @description 是否派单到待分配列表
 * @param {AllotTypeEnum} allotType 指派类型
 * @return {Boolean}
 */
export function isAllotWait(allotType: AllotTypeEnum): boolean {
  return allotType === AllotTypeEnum.Wait
}

/**
 * @description 是否为工单管理员
 * @param {Record} auth 权限数据
 * @return {Boolean}
 */
export function isTaskManager(auth: Record<AuthEnum | string, number>): boolean {
  return auth?.[AuthEnum.TASK_VIEW] == AuthValueEnum.All
}

/**
 * @description: 获取工单id
 * @param {any} task 工单数据
 * @return {String | null}
*/
export function getTaskId(task: any): string {
	return task?.id || task?.iid || task?.UUID || task?.taskId || ''
}

/**
 * @description: 获取工单类型id
 * @param {any} task 工单数据
 * @return {String | null}
*/
export function getTemplateId(task: any): string {
	return task?.templateId || ''
}

/**
 * @description 指派工单
 * @param {EsTask} task 工单信息
 * @param {Boolean} isRestructAllot 是否开启新版指派
 * @return {void}
 */  
export function allotTaskJump(task: EsTask, isRestructAllot: boolean): void {
  // @ts-ignore
  Vue.prototype.$track.clickStat(Vue.prototype.$track.formatParams('TASK_ALLOT'));
  
  // 工单id
  const taskId: string = getTaskId(task)
  // 是否开启工单灰度
  const isUserTaskGray = InitData?.isUserTaskGrayFunction || false
  
  // 开启了新版工单且开启了新版工单指派 则跳转到工单详情指派
  return openTabForTaskView(taskId, true, false, true)
  // if (isUserTaskGray && isRestructAllot) return openTabForTaskView(taskId, true, false, true)
  
  // // 打开工单指派tab
  // return openTabForTaskAllot(taskId)
}

export function allowModifyPlanTimeJudgeHandler(task?: EsTask): boolean {
  if (!task) return false
  
  return !isPaused(task) && !isInApprove(task)
}

export default {
  checkApprove,
  getFieldValue2string,
  isCreator,
  getTaskId
}